<?php
/**
 * HTTP响应类
 *
 * @category   ORG
 * @package    ORG
 * @subpackage Response
 * @author     海啸 <459103503@qq.com>
 */
class HttpResponse
{
    const DEFAULT_CHARSET = 'utf-8';
    const DEFAULT_EXPIRES = 1000;

    // [Informational 1xx]
    const HTTP_CONTINUE = 100;
    const HTTP_SWITCHING_PROTOCOLS = 101;

    // [Successful 2xx]
    const HTTP_OK = 200;
    const HTTP_CREATED = 201;
    const HTTP_ACCEPTED = 202;
    const HTTP_NONAUTHORITATIVE_INFORMATION = 203;
    const HTTP_NO_CONTENT = 204;
    const HTTP_RESET_CONTENT = 205;
    const HTTP_PARTIAL_CONTENT = 206;

    // [Redirection 3xx]
    const HTTP_MULTIPLE_CHOICES = 300;
    const HTTP_MOVED_PERMANENTLY = 301;
    const HTTP_FOUND = 302;
    const HTTP_SEE_OTHER = 303;
    const HTTP_NOT_MODIFIED = 304;
    const HTTP_USE_PROXY = 305;
    const HTTP_UNUSED = 306;
    const HTTP_TEMPORARY_REDIRECT = 307;

    // [Client Error 4xx]
    const HTTP_BAD_REQUEST = 400;
    const HTTP_UNAUTHORIZED = 401;
    const HTTP_PAYMENT_REQUIRED = 402;
    const HTTP_FORBIDDEN = 403;
    const HTTP_NOT_FOUND = 404;
    const HTTP_METHOD_NOT_ALLOWED = 405;
    const HTTP_NOT_ACCEPTABLE = 406;
    const HTTP_PROXY_AUTHENTICATION_REQUIRED = 407;
    const HTTP_REQUEST_TIMEOUT = 408;
    const HTTP_CONFLICT = 409;
    const HTTP_GONE = 410;
    const HTTP_LENGTH_REQUIRED = 411;
    const HTTP_PRECONDITION_FAILED = 412;
    const HTTP_REQUEST_ENTITY_TOO_LARGE = 413;
    const HTTP_REQUEST_URI_TOO_LONG = 414;
    const HTTP_UNSUPPORTED_MEDIA_TYPE = 415;
    const HTTP_REQUESTED_RANGE_NOT_SATISFIABLE = 416;
    const HTTP_EXPECTATION_FAILED = 417;

    // [Server Error 5xx]
    const HTTP_INTERNAL_SERVER_ERROR = 500;
    const HTTP_NOT_IMPLEMENTED = 501;
    const HTTP_BAD_GATEWAY = 502;
    const HTTP_SERVICE_UNAVAILABLE = 503;
    const HTTP_GATEWAY_TIMEOUT = 504;
    const HTTP_VERSION_NOT_SUPPORTED = 505;

    private $_recommendedStatusDesc = array(
        // [Informational 1xx]
        100 => 'Continue',
        101 => 'Switching Protocols',

        // [Successful 2xx]
        200 => 'OK',
        201 => 'Created',
        202 => 'Accepted',
        203 => 'Non-Authoritative Information',
        204 => 'No Content',
        205 => 'Reset Content',
        206 => 'Partial Content',

        // [Redirection 3xx]
        300 => 'Multiple Choices',
        301 => 'Moved Permanently',
        302 => 'Found',
        303 => 'See Other',
        304 => 'Not Modified',
        305 => 'Use Proxy',
        306 => '(Unused)',
        307 => 'Temporary Redirect',

        // [Client Error 4xx]
        400 => 'Bad Request',
        401 => 'Unauthorized',
        402 => 'Payment Required',
        403 => 'Forbidden',
        404 => 'Not Found',
        405 => 'Method Not Allowed',
        406 => 'Not Acceptable',
        407 => 'Proxy Authentication Required',
        408 => 'Request Timeout',
        409 => 'Conflict',
        410 => 'Gone',
        411 => 'Length Required',
        412 => 'Precondition Failed',
        413 => 'Request Entity Too Large',
        414 => 'Request-URI Too Long',
        415 => 'Unsupported Media Type',
        416 => 'Requested Range Not Satisfiable',
        417 => 'Expectation Failed',

        // [Server Error 5xx]
        500 => 'Internal Server Error',
        501 => 'Not Implemented',
        502 => 'Bad Gateway',
        503 => 'Service Unavailable',
        504 => 'Gateway Timeout',
        505 => 'HTTP Version Not Supported'
    );

    /**
     * HTTP protocol
     *
     * @var string
     */
    protected $protocol;

    /**
     * Content type of this response
     *
     * @var string
     */
    protected $contentType = 'text/html';

    /**
     * Whether attach Etag to header
     *
     * @var bool
     */
    protected $enableEtag = false;

    /**
     * charset of this response
     *
     * @var string
     */
    protected $charset = '';

    /**
     * content of this response
     *
     * @var string
     */
    protected $body = '';


    /**
     * @var int status code
     */
    protected $statusCode = 200;

    /**
     * @var string leer string
     * means it will be looked up from the $_recommendedStatusDesc list above
     */
    protected $statusDesc = '';


    /**
     * setted haders
     *
     * @var array
     */
    protected $headers = [];

    /**
     * construct
     *
     * @param string $protocol    protocol
     * @param string $charset     charset
     * @param string $contentType contentType
     */
    public function __construct($protocol='HTTP/1.1',
        $charset = HttpResponse::DEFAULT_CHARSET, $contentType=''
    ) {
        $this->contentType = $contentType;
        $this->charset = $charset;
        $this->protocol = $protocol;
    }

    /**
     * set the body of http response
     *
     * @param string $body body
     *
     * @return HttpResponse
     */
    public function setBody($body)
    {
        if (strcasecmp($this->contentType, 'application/json') ==0) {
            if (is_array($body) || is_object($body)) {
                $this->body = json_encode($body);
            } else {
                $this->body = $body;
            }
        } else {
            $this->body = $body;
        }

        return $this;
    }

    /**
     * get the body of http response
     *
     * @return string body
     */
    public function getBody()
    {
        return $this->body;
    }

    /**
     * 设置eTag开启
     *
     * @param bool $enabled enabled
     *
     * @return HttpResponse
     */
    public function etag($enabled=true)
    {
        $this->enableEtag = $enabled;
        return $this;
    }

    /**
     * 设置最近更新时间
     *
     * @param int $timestamp timestamp
     *
     * @return HttpResponse
     */
    public function setLastModified($timestamp)
    {
        $this->addHeader('Last-Modified', date('r', $timestamp));
        return $this;
    }

    /**
     * 设置过期头
     *
     * @param int|string $expires expires
     *
     * @return HttpResponse
     */
    public function setExpires($expires=self::DEFAULT_EXPIRES)
    {
        $this->addHeader('Cache-Control', 'max-age=' . $expires, true)
            ->addHeader('Expires', date('r', time() + $expires))
            ->setLastModified(time());
        return $this;
    }

    /**
     * Send 304 Header
     *
     * @return HttpResponse
     */
    public function notModified()
    {
        $this->body = '';
        return $this->setStatus(self::HTTP_NOT_MODIFIED);
    }

    /**
     * Send 400 Header
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function badRequest($msg = '')
    {
        return $this->setStatus(self::HTTP_BAD_REQUEST, $msg);
    }

    /**
     * Send 401
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function unauthorized($msg = '')
    {
        return $this->setStatus(self::HTTP_UNAUTHORIZED, $msg);
    }

    /**
     * 设置404 HTTP头
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function notFound($msg = '')
    {
        return $this->setStatus(self::HTTP_NOT_FOUND, $msg);
    }

    /**
     * 设置403 HTTP头
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function forbidden($msg = '')
    {
        return $this->setStatus(self::HTTP_FORBIDDEN, $msg);
    }

    /**
     * 设置409 HTTP头
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function conflict($msg = '')
    {
        return $this->setStatus(self::HTTP_CONFLICT, $msg);
    }

    /**
     * Internal server error
     *
     * @param string $msg Message
     *
     * @return HttpResponse
     */
    public function internalError($msg = '')
    {
        return $this->setStatus(self::HTTP_INTERNAL_SERVER_ERROR, $msg);
    }

    /**
     * 发送 406 的 HTTP 头部信息
     *
     * @return HttpResponse
     */
    public function notAcceptable()
    {
        $this->body = '';
        return $this->setStatus(self::HTTP_NOT_ACCEPTABLE);
    }

    /**
     * 强制浏览器不缓存
     *
     * @return HttpResponse
     */
    public function noCache()
    {
        $this->addHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT")
            ->addHeader("Cache-Control", "no-cache, must-revalidate")
            ->addHeader("Pragma", "no-cache");
        return $this;
    }

    /**
     * 301 Moved Permanently
     *
     * @param string $url 转向的地址
     *
     * @return HttpResponse
     */
    public function moved($url)
    {
        $this->body = '';
        return $this->setStatus(self::HTTP_MOVED_PERMANENTLY)
            ->addHeader('Location', $url);
    }

    /**
     * 302 Found
     *
     * @param string $url 转向的地址
     *
     * @return HttpResponse
     */
    public function redirect($url)
    {
        $this->body = '';
        $this->setStatus(self::HTTP_FOUND)
            ->addHeader('Location', $url);
        return $this;
    }

    /**
     * set status code and message
     *
     * @param int    $code code
     * @param string $desc desc
     *
     * @return HttpResponse
     */
    public function setStatus($code, $desc='')
    {
        $this->setStatusCode($code);
        if ($desc == '') {
            $desc = $this->_recommendedStatusDesc[$code];
        }
        $this->setStatusDesc($desc);
        return $this;
    }

    /**
     * get status code
     *
     * @return int
     */
    public function getStatusCode()
    {
        return $this->statusCode;
    }

    /**
     * get status description
     *
     * @return null|string
     */
    public function getStatusDesc()
    {
        if (empty($this->statusDesc)) {
            $this->statusDesc = $this->_recommendedStatusDesc[$this->statusCode];
        }
        return $this->statusDesc;
    }


    /**
     * set the status code of response
     *
     * @param int $code code
     *
     * @return HttpResponse
     */
    public function setStatusCode($code)
    {
        $this->statusCode = $code;
        return $this;
    }

    /**
     * set the description of the status
     *
     * @param string $statusDesc status description
     *
     * @return HttpResponse
     */
    public function setStatusDesc($statusDesc)
    {
        $this->statusDesc = $statusDesc;
        return $this;
    }

    /**
     * Set content type
     *
     * @param string $type type
     *
     * @return HttpResponse
     */
    public function setContentType($type)
    {
        $this->contentType = $type;
        return $this;
    }

    /**
     * Send an error message to client
     *
     * @param int    $code code
     * @param string $desc description
     *
     * @return HttpResponse
     */
    public function errMessage($code, $desc='')
    {
        return $this->setStatus($code, $desc);
    }

    /**
     * Add a header item
     *
     * @param string $key     Header key
     * @param string $val     Header value
     * @param bool   $replace replace
     *
     * @return HttpResponse
     */
    public function addHeader($key, $val, $replace=false)
    {
        $val = str_replace(array("\r", "\n"), array('', ''), $val);
        $this->headers[$key] = [$val, $replace];
        return $this;
    }

    /**
     * 获得指定的header信息
     *
     * @param string $key Header 名称
     *
     * @return string
     */
    public function getHeader($key)
    {
        return isset($this->headers[$key]) ? $this->headers[$key][0] : null;
    }

    /**
     * 获得所有的 Header 信息
     *
     * @return array
     */
    public function getAllHeaders()
    {
        $protocol       = $this->protocol. " {$this->getStatusCode()} {$this->getStatusDesc()}";
        $contentType    = "Content-Type: {$this->contentType}; charset={$this->charset}";
        $poweredBy      = 'X-Powered-By: Scenter';
        $etag           = 'ETag: ' . md5($this->body);
        $reportInfo     = 'X-System-Report: ' . sprintf(
            'time=%.2f MS, memory=%.2f MB',
            (microtime(true) - START_TIME) * 1000,
            memory_get_usage() / 1024 / 1024
        );

        $arr[$protocol]     = true;
        $arr[$contentType]  = true;
        $arr[$etag]         = true;
        $arr[$poweredBy]    = true;
        $arr[$reportInfo]   = true;


        foreach ($this->headers as $key=>$val) {
            $str = "{$key}: {$val[0]}";
            $arr[$str] = isset($val[1]) && $val[1];
        }

        return $arr;
    }

    /**
     * 设置头信息
     *
     * @return HttpResponse
     */
    public function setHeaders()
    {
        foreach ($this->getAllHeaders() as $string=>$replace) {
            header($string, $replace);
        }

        return $this;
    }


}